package cn.lcc.utils.utils.method;


import cn.lcc.utils.commom.annotation.Mapping;
import cn.lcc.utils.utils.method.handle.Handler;
import cn.lcc.utils.utils.method.handle.SimpleHandler;
import org.springframework.web.servlet.HandlerMapping;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息处理映射
 */
public abstract class AbstractHandlerMapping implements HandlerMapping {

    private final Map<Object, Handler> handlerMap = new HashMap<>(64);

    /**
     * 将Endpoint中被@Mapping标记的方法注册到映射表
     */
    protected synchronized void registerHandlers(Object bean) {
        Class<?> beanClass = bean.getClass();
        Method[] methods = beanClass.getDeclaredMethods();
        for (Method method : methods) {
            Mapping mapping = method.getAnnotation(Mapping.class);
            if (mapping != null) {
                String desc = mapping.desc();
                int[] types = mapping.types();
                Handler handler;
                handler = new SimpleHandler(bean, method, desc, true);
                for (int type : types) {
                    handlerMap.put(type, handler);
                }
            }
        }
    }

}